package com.xyy.saas.payment.query.core.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jddglobal.open.client.JddClient;
import com.jddglobal.open.request.base.JddRequest;
import com.jddglobal.open.response.base.BaseJddResponse;
import com.jddglobal.open.support.config.EsuSdkConfig;
import com.jddglobal.open.support.util.JacksonUtils;
import com.xyy.saas.payment.adpater.jd.common.JDConstants;
import com.xyy.saas.payment.adpater.jdCredit.req.*;
import com.xyy.saas.payment.adpater.jdCredit.resp.*;
import com.xyy.saas.payment.common.Constants;
import com.xyy.saas.payment.common.exception.PaymentException;
import com.xyy.saas.payment.cores.enums.ResultCodeEnum;
import com.xyy.saas.payment.cores.param.PinganLoanDataMerchantsInfo;
import com.xyy.saas.payment.cores.param.PinganLoanDataMonthlyOperation;
import com.xyy.saas.payment.cores.param.PinganLoanDatasToSendDto;
import com.xyy.saas.payment.cores.vo.FinanceAccountInfoVo;
import com.xyy.saas.payment.cores.vo.ResultVO;
import com.xyy.saas.payment.util.AmountCastUtil;
import com.xyy.saas.payment.util.ApolloUtil;
import com.xyy.saas.payment.util.DateUtil;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.concurrent.ThreadSafe;
import java.math.BigDecimal;
import java.util.*;

/**
 * @ClassName kkk
 * @Author renwg
 * @Date 2024/6/6 15:18
 * @Version 1.0
 */
@Slf4j
public class SmapiDemoInvoker {
    public static void main(String[] args) throws Exception {
        // 手动设置 测试环境配置文件，切勿将线上配置，提到开发分支了！！
        EsuSdkConfig.DEFAULT_CONFIG_FILE = "jdd_sdk_test_config.properties";

        // 设置配置文件路径，默认为如下值，可不设置
//        pushCustData();
        queryLoanReq();
//        pay();
//        pushOrderStatus();
//        queryOrderStatus();
//        queryCustInfo("1500124946",null);
//        refund();
//        pushLoanSceneData();
    }

    public static void pushLoanSceneData() throws PaymentException {
        PushLoanSceneDataRequest request = new PushLoanSceneDataRequest();
        request.setReqNo(new Date().getTime() + "");
        request.setReqDate(DateUtil.date2String(new Date(), DateUtil.YYYYMMDDHHMMSS));
        request.setProductCode(Constants.JD_CREDIT_PRODUCT_CODE);
        request.setPartnerCode(Constants.JD_CREDIT_PARTNER_CODE);
        request.setCoreCompanyCode(Constants.JD_CREDIT_COMPANY_CODE);
        List<LoanSceneData> sceneDataList = new ArrayList<>();
        LoanSceneData sceneData = new LoanSceneData();
        sceneData.setCustCode("1500124676");
        sceneData.setFirstOrderCreateTime("20240531000000");
        sceneData.setLastOrderCreateTime("20240731000000");
        List<OrdersInfo> ordersInfos = new ArrayList<>();
        OrdersInfo ordersInfo = new OrdersInfo();
        ordersInfo.setOrderCreateMth("2024-07");
        ordersInfo.setOrderCnt(10);
        ordersInfo.setRefundCnt(2);
        ordersInfo.setPaidCnt(10);
        ordersInfo.setPaidAmount(BigDecimal.valueOf(120));
        ordersInfo.setOrderAmount(BigDecimal.valueOf(200));
        ordersInfo.setRefundAmount(BigDecimal.valueOf(80));
        ordersInfos.add(ordersInfo);
        sceneData.setOrderList(ordersInfos);
        sceneDataList.add(sceneData);
        request.setSceneDataList(sceneDataList);
        System.out.println("pushLoanSceneData 入参："+JSON.toJSONString(request));
        BaseJddResponse response = jddExecute(request);
        System.out.println("pushLoanSceneData 出参："+JSON.toJSONString(response));
    }

    public static void refund() throws PaymentException {
        RefundApplyReq applyReq = buildRefundApplyReq();
        BaseJddResponse response = jddExecute(applyReq);
        System.out.println(response);
    }

    private static RefundApplyReq buildRefundApplyReq() {
        //发起退款
        RefundApplyReq applyReq = new RefundApplyReq();
        applyReq.setReqNo(new Date().getTime() + "");
        applyReq.setReqDate(DateUtil.date2String(new Date(), DateUtil.YYYYMMDDHHMMSS));
        applyReq.setBizNo(new Date().getTime() + "");
        applyReq.setProductCode(Constants.JD_CREDIT_PRODUCT_CODE);
        applyReq.setPartnerCode(Constants.JD_CREDIT_PARTNER_CODE);
        applyReq.setCustCode("1500124676");
//        applyReq.setSettleUserCode("CoreXYY20240607");
        applyReq.setOrderCode("1805165252564746328");
        applyReq.setRefundDesc("退货");
        applyReq.setRefundAmount(BigDecimal.valueOf(100));
        //京户通监管账户号。待财务提供
        applyReq.setPayAccountNo("91100078142344848709");
        applyReq.setPayAccountName("小药药核心企业京户通账户");
        //京户通监管账户开户行。待财务提供
        applyReq.setPayOpenBank("平安银行深圳坂田支行");
        applyReq.setReceiveAccountNo(Constants.RECEIVE_ACCOUNT_NO);
        applyReq.setReceiveAccountName(Constants.RECEIVE_ACCOUNT_NAME);
        applyReq.setNotifyUrl("https://payment.test.ybm100.com/platform/jd/jdCredit/refundNotice");
        applyReq.setRefundPayWay(Constants.JD_CREDIT_REFUND_PAY_WAY);
        // 风控参数
//        applyReq.setRiskControlParams();
        // 扩展参数
        return applyReq;
    }

    public static <T extends BaseJddResponse> T jddExecute(JddRequest request) throws PaymentException {
        //请求京东
        JddClient jddClient = EsuSdkConfig.getJddClient();
        try {
            log.info("入参：" + JacksonUtils.toJson(request));
            T response = jddClient.execute(request);
            log.info("出参：" + JacksonUtils.toJson(response));
            JSONObject jsonObject = JSONObject.parseObject(response.getBizContent());
            String resCode = jsonObject.getString("resCode");
            if (!JDConstants.JD_CREDIT_SUCCESS_CODE.equals(resCode)) {
                throw new PaymentException(jsonObject.getString("resDesc"));
            }
            return (T) jsonObject.getObject("data", response.getClass());
        } catch (Exception e) {
            log.error("异常：", e);
            throw new PaymentException(ResultCodeEnum.CHANNEL_CONNECT_ERROR.getCode(), e.getMessage());
        }
    }


    public static void queryLoanReq() {
        QueryLoanReq queryLoanReq = new QueryLoanReq();
        queryLoanReq.setReqNo(System.currentTimeMillis() + "");
        queryLoanReq.setReqDate(DateUtil.date2String(new Date(), DateUtil.YYYYMMDDHHMMSS));
        queryLoanReq.setProductCode("25199");
//        queryLoanReq.setLoanNo("cgrzeL2024061701000016");
        queryLoanReq.setOrderCode("18257378488929485091");

        //请求京东
        JddClient jddClient = EsuSdkConfig.getJddClient();
        //请求京东
        try {
            System.out.println(JSON.toJSONString(queryLoanReq));
            BaseJddResponse result = jddClient.execute(queryLoanReq);
            System.out.println(JSON.toJSONString(result));
            LoanInfoResponse response = JSONObject.parseObject(result.getBizContent()).getObject("data", LoanInfoResponse.class);
            System.out.println("response::" +JSON.toJSONString( response));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void pay() {
        JddClient jddClient = EsuSdkConfig.getJddClient();
        // 发起支付
        PayOrderReq payOrderReq = new PayOrderReq();
        payOrderReq.setReqNo(new Date().getTime() + "");
        payOrderReq.setReqDate(DateUtil.date2String(new Date(), DateUtil.YYYYMMDDHHMMSS));
        payOrderReq.setBizNo(new Date().getTime() + "");
        payOrderReq.setProductCode(Constants.JD_CREDIT_PRODUCT_CODE);
        payOrderReq.setPartnerCode(Constants.JD_CREDIT_PARTNER_CODE);
        payOrderReq.setCustCode("1500124676");
        payOrderReq.setCoreCompanyCode(Constants.JD_CREDIT_COMPANY_CODE);
        payOrderReq.setOrderCode("YBM1203443347013");
        payOrderReq.setOrderAmount("1000");
        payOrderReq.setApplyAmount("1000");
        payOrderReq.setCreateDate(DateUtil.date2String(new Date(), DateUtil.YYYYMMDDHHMMSS));
        payOrderReq.setExpireDate("20241016125958");
        payOrderReq.setOrderDesc("订单描述");
        payOrderReq.setOrderStatus("CREATED");
        payOrderReq.setPayStatus("UNPAY");
        payOrderReq.setReceiveName("上海京汇小额贷款有限公司");
        payOrderReq.setReceiveAccount("11050171360000000498");
        Map<String, Object> riskControlParams = new HashMap<>();
        Map<String, Object> orderDetail = new HashMap<>();
        riskControlParams.put("orderDetail", orderDetail);
        Map<String, Object> wayInfos = new HashMap<>();
        riskControlParams.put("wayInfos", wayInfos);
        Map<String, Object> orderGoodInfo = new HashMap<>();
        riskControlParams.put("orderGoodInfo", orderGoodInfo);

        payOrderReq.setRiskControlParams(riskControlParams);
        payOrderReq.setFinanceNotifyUrl("https://payment.test.ybm100.com/platform/jd_credit/jdcdtNotice");
        payOrderReq.setRepayNotifyUrl("https://payment.test.ybm100.com/platform/jd_credit/jdRepayNotify");
        payOrderReq.setChannelSource("APPLET");
        Map<String, Object> attachment = new HashMap<>();
        payOrderReq.setAttachment(attachment);

        try {
//            String str = "{\"apiMethod\":\"/smapi/v1/nav/pushPayOrder\",\"applyAmount\":\"1420.00\",\"attachment\":{},\"bizNo\":\"1803619777919320087\",\"channelSource\":\"PC\",\"coreCompanyCode\":\"CoreXYY20240607\",\"createDate\":\"20240620104359\",\"custCode\":\"1500124676\",\"expireDate\":\"20240621104355\",\"financeNotifyUrl\":\"https://payment.test.ybm100.com/platform/jd/jdCredit/payNotice\",\"jsonParams\":\"{\\\"reqNo\\\":\\\"1803619777919320087\\\",\\\"reqDate\\\":\\\"20240620104359\\\",\\\"bizNo\\\":\\\"1803619777919320087\\\",\\\"productCode\\\":\\\"25199\\\",\\\"partnerCode\\\":\\\"TentXYY20240607\\\",\\\"custCode\\\":\\\"1500124676\\\",\\\"coreCompanyCode\\\":\\\"CoreXYY20240607\\\",\\\"orderCode\\\":\\\"1803619777835434020\\\",\\\"orderAmount\\\":\\\"1420.00\\\",\\\"applyAmount\\\":\\\"1420.00\\\",\\\"createDate\\\":\\\"20240620104359\\\",\\\"expireDate\\\":\\\"20240621104355\\\",\\\"orderDesc\\\":\\\"药品\\\",\\\"orderStatus\\\":\\\"CREATED\\\",\\\"payStatus\\\":\\\"UNPAY\\\",\\\"receiveName\\\":\\\"上海京汇小额贷款有限公司\\\",\\\"receiveAccount\\\":\\\"11050171360000000498\\\",\\\"riskControlParams\\\":{\\\"orderDetail\\\":{\\\"wayInfos\\\":{\\\"orderGoodInfo\\\":{\\\"orderAmount\\\":\\\"1420.00\\\",\\\"orderId\\\":\\\"1803619777835434020\\\",\\\"orderPayable\\\":\\\"1420.00\\\",\\\"orderPaiedAmount\\\":\\\"1420.00\\\",\\\"cnt\\\":1,\\\"sellerName\\\":\\\"\\\",\\\"orderStatus\\\":\\\"CREATED\\\",\\\"buyerName\\\":\\\"\\\",\\\"orderDate\\\":\\\"20240620\\\",\\\"payStatus\\\":\\\"UNPAY\\\",\\\"orderDescription\\\":\\\"药品\\\"}}}},\\\"financeNotifyUrl\\\":\\\"https://payment.test.ybm100.com/platform/jd/jdCredit/payNotice\\\",\\\"repayNotifyUrl\\\":\\\"https://payment.test.ybm100.com/platform/jd/jdCredit/contractNotice\\\",\\\"channelSource\\\":\\\"PC\\\",\\\"attachment\\\":{}}\",\"orderAmount\":\"1420.00\",\"orderCode\":\"1803619777835434020\",\"orderDesc\":\"药品\",\"orderStatus\":\"CREATED\",\"partnerCode\":\"TentXYY20240607\",\"payStatus\":\"UNPAY\",\"productCode\":\"25199\",\"receiveAccount\":\"11050171360000000498\",\"receiveName\":\"上海京汇小额贷款有限公司\",\"repayNotifyUrl\":\"https://payment.test.ybm100.com/platform/jd/jdCredit/contractNotice\",\"reqDate\":\"20240620104359\",\"reqNo\":\"1803619777919320087\",\"requestTime\":\"20240620024359352\",\"responseClass\":\"com.xyy.saas.payment.adpater.jdCredit.resp.SmapiResponse\",\"riskControlParams\":{\"orderDetail\":{\"wayInfos\":{\"orderGoodInfo\":{\"buyerName\":\"\",\"cnt\":1,\"orderAmount\":\"1420.00\",\"orderDate\":\"20240620\",\"orderDescription\":\"药品\",\"orderId\":\"1803619777835434020\",\"orderPaiedAmount\":\"1420.00\",\"orderPayable\":\"1420.00\",\"orderStatus\":\"CREATED\",\"payStatus\":\"UNPAY\",\"sellerName\":\"\"}}}}}";
//            PayOrderReq payOrderReq1 = JSONObject.parseObject(str, PayOrderReq.class);
//            payOrderReq1.setBizNo(System.currentTimeMillis()+"");
            System.out.println("pay 入参：" + JSON.toJSONString(payOrderReq));
            BaseJddResponse result = jddClient.execute(payOrderReq);
            System.out.println("pay 出参：" + JSON.toJSONString(result));
            JSONObject jsonObject = JSONObject.parseObject(result.getBizContent());
            jsonObject.get("data");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 客户场景信息推送
     *
     * @return
     * @throws PaymentException
     */
    public static void pushCustData() throws PaymentException {
        PushCustSceneDataRequest pushCustSceneDataRequest = new PushCustSceneDataRequest();
        pushCustSceneDataRequest.setReqNo(System.currentTimeMillis() + "");
        pushCustSceneDataRequest.setReqDate(DateUtil.date2String(new Date(), DateUtil.YYYYMMDDHHMMSS));
        pushCustSceneDataRequest.setBizNo(System.currentTimeMillis() + "");
        pushCustSceneDataRequest.setProductCode(Constants.JD_CREDIT_PRODUCT_CODE);
        pushCustSceneDataRequest.setCoreCompanyCode(Constants.JD_CREDIT_COMPANY_CODE);
        pushCustSceneDataRequest.setPartnerCode(Constants.JD_CREDIT_PARTNER_CODE);
        pushCustSceneDataRequest.setCustCode("1500124948");//merchantId
        pushCustSceneDataRequest.setCustName("增石（辽宁）物产有限公司");
        pushCustSceneDataRequest.setCustType("COMPANY");
        pushCustSceneDataRequest.setCustCertType("USCC");
        pushCustSceneDataRequest.setCustCertNo("9121010377480036X2");//统一社会信用代码
        pushCustSceneDataRequest.setLegalName("叶老板");
        pushCustSceneDataRequest.setLegalCertType("ID_CARD");
        pushCustSceneDataRequest.setLegalCertNo("412722198908063117");
        pushCustSceneDataRequest.setLegalPhone("15736790114");
        //第一次下单时间
        pushCustSceneDataRequest.setFirstOrderCreateTime("20240610153230");
        //最后一次下单时间
        pushCustSceneDataRequest.setLastOrderCreateTime("20240611153230");
//        pushCustSceneDataRequest.setRegistrationDuration();//非必填
//        pushCustSceneDataRequest.setCompanyLevel();//非必填
//        pushCustSceneDataRequest.setRiskControlParams();//非必填

        pushCustSceneDataRequest.setOrderList(buildOrderList());
//        pushCustSceneDataRequest.setAttachment();//非必填
        pushCustSceneDataRequest.setNotifyUrl("https://payment.test.ybm100.com/platform/jd/jdCredit/contractNotice");
        pushCustSceneDataRequest.setChannelSource("H5");
//        pushCustSceneDataRequest.setExt();//非必填
        JddClient jddClient = EsuSdkConfig.getJddClient();
        //请求京东
        try {
            System.out.println(JacksonUtils.toJson(pushCustSceneDataRequest));
            BaseJddResponse result = jddClient.execute(pushCustSceneDataRequest);
            System.out.println(JacksonUtils.toJson(result));
            String bizContent = result.getBizContent();
            PushCustSceneDataResp resp = JSONObject.parseObject(bizContent, PushCustSceneDataResp.class);

            System.out.println(resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static List<OrdersInfo> buildOrderList() {
        List<OrdersInfo> list = new ArrayList<>();
        OrdersInfo ordersInfo = new OrdersInfo();
        ordersInfo.setOrderCreateMth("202406");
        ordersInfo.setOrderAmount(new BigDecimal("800000.92"));
        ordersInfo.setOrderCnt(200);
        ordersInfo.setRefundAmount(new BigDecimal("200.12"));
        ordersInfo.setRefundCnt(2);
        ordersInfo.setPaidAmount(new BigDecimal("799800.8"));
        ordersInfo.setPaidCnt(198);
        ordersInfo.setInvoiceAmount(new BigDecimal("799800.8"));
        list.add(ordersInfo);
        return list;
    }

    /**
     * 查询客户信息
     *
     * @throws PaymentException
     */
    public static FinanceAccountInfoVo queryCustInfo(String custCode, String thirdApplyNo) throws PaymentException {
        QueryCustInfoReq queryCustInfoReq = new QueryCustInfoReq();
        queryCustInfoReq.setReqNo(System.currentTimeMillis() + "");
        queryCustInfoReq.setReqDate(DateUtil.date2String(new Date(), DateUtil.YYYYMMDDHHMMSS));
        queryCustInfoReq.setProductCode(Constants.JD_CREDIT_PRODUCT_CODE);
        queryCustInfoReq.setPartnerCode(Constants.JD_CREDIT_PARTNER_CODE);
        queryCustInfoReq.setCustCode(custCode);
        queryCustInfoReq.setChannelSource("APPLET");

        //请求京东
        JddClient jddClient = EsuSdkConfig.getJddClient();
        //请求京东
        try {
            System.out.println(JacksonUtils.toJson(queryCustInfoReq));
            BaseJddResponse result = jddClient.execute(queryCustInfoReq);
            System.out.println(JacksonUtils.toJson(result));
            JSONObject jsonObject = JSONObject.parseObject(result.getBizContent());
            JSONObject data = jsonObject.getJSONObject("data");
            QueryCustInfoResp data1 = jsonObject.getObject("data", QueryCustInfoResp.class);
            QueryCustInfoResp queryCustInfoResp1 = JSONObject.parseObject(data.toJSONString(), QueryCustInfoResp.class);
            ApiResponse<QueryCustInfoResp> apiResponse = JSON.parseObject(result.getBizContent(), ApiResponse.class);
            QueryCustInfoResp queryCustInfoResp = apiResponse.getData();
            return FinanceAccountInfoVo.builder().approveAmount(AmountCastUtil.formatBigDecimal2PercentInt(queryCustInfoResp.getCreditLimit())).thirdApplyNo(thirdApplyNo).availableAmount(AmountCastUtil.formatBigDecimal2PercentInt(queryCustInfoResp.getRemainLimit())).build();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 推送订单状态
     *
     * @throws PaymentException
     */
    public static void pushOrderStatus() throws PaymentException {
        PushOrderStatusReq pushOrderStatusReq = new PushOrderStatusReq();
        pushOrderStatusReq.setReqNo(System.currentTimeMillis() + "");
        pushOrderStatusReq.setReqDate(DateUtil.date2String(new Date(), DateUtil.YYYYMMDDHHMMSS));
        pushOrderStatusReq.setProductCode(Constants.JD_CREDIT_PRODUCT_CODE);
        pushOrderStatusReq.setPartnerCode(Constants.JD_CREDIT_PARTNER_CODE);
        pushOrderStatusReq.setOrderStatus("CANCEL");
        pushOrderStatusReq.setOrderCode("1803396467780485138");
        //请求京东
        JddClient jddClient = EsuSdkConfig.getJddClient();
        //请求京东
        try {
            BaseJddResponse result = jddClient.execute(pushOrderStatusReq);
            System.out.println(JacksonUtils.toJson(result));
            JSONObject jsonObject = JSONObject.parseObject(result.getBizContent());
            String resCode = jsonObject.getString("resCode");
            if (!JDConstants.JD_CREDIT_SUCCESS_CODE.equals(resCode)) {
                throw new PaymentException(jsonObject.getString("resDesc"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //PayOrderStatusResp
    }

    public static void queryOrderStatus() throws PaymentException {
        QueryOrderStatusReq queryOrderStatusReq = new QueryOrderStatusReq();
        queryOrderStatusReq.setReqNo(System.currentTimeMillis() + "");
        queryOrderStatusReq.setReqDate(DateUtil.date2String(new Date(), DateUtil.YYYYMMDDHHMMSS));
        queryOrderStatusReq.setProductCode(Constants.JD_CREDIT_PRODUCT_CODE);
        queryOrderStatusReq.setPartnerCode(Constants.JD_CREDIT_PARTNER_CODE);
        queryOrderStatusReq.setOrderCode("1803979217688330298");
//        pushOrderStatusReq.setOrderStatus();

        //请求京东
        JddClient jddClient = EsuSdkConfig.getJddClient();
        //请求京东
        try {
            BaseJddResponse result = jddClient.execute(queryOrderStatusReq);
            System.out.println(JacksonUtils.toJson(result));
            JSONObject jsonObject = JSONObject.parseObject(result.getBizContent());
            String resCode = jsonObject.getString("resCode");
            if (!JDConstants.JD_CREDIT_SUCCESS_CODE.equals(resCode)) {
                throw new PaymentException(jsonObject.getString("resDesc"));
            }
            PayOrderStatusResp data = jsonObject.getObject("data", PayOrderStatusResp.class);
            System.out.println("");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //PayOrderStatusResp
    }
}